package com.leyou.user.service.impl;

import com.leyou.test.enums.ExceptionEnum;
import com.leyou.test.exceptions.LyException;
import com.leyou.user.dot.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.IUserService;
import com.leyou.utils.BeanHelper;
import com.leyou.utils.JsonUtils;
import com.leyou.utils.RegexUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.constants.MQConstants.Exchange.*;
import static com.leyou.constants.MQConstants.RoutingKey.*;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;


    /**
     * 实现用户数据的校验
     *
     * @param data 要校验的数据
     * @param type 要校验的数据类型：1，用户名；2，手机
     * @return 返回结果  查不到:true;能查到:false
     */
    @Override
    public Boolean checkUserData(String data, Integer type) {
        //校验data是否为空
        if (StringUtils.isBlank(data)) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        User user = new User();
        if (1 == type) {
            //data为用户名
            user.setUsername(data);
        } else if (2 == type) {
            //data为手机
            user.setPhone(data);
        } else {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //根据data查询user的数量,如果为0,则不存在,返回true;否则,返回false
        int count = 0;
        try {
            count = userMapper.selectCount(user);
        } catch (Exception e) {
            throw new LyException(500, "用户数据验证失败,异常信息为:" + e.getMessage(), e);
        }
        return count == 0;
    }

    //发送手机验证码,参数的key的前缀
    private static final String KEY_PREFIX = "user:verify:phone:";

    /**
     * 生成短信验证码
     *
     * @param phone 用户手机号码
     */
    @Override
    public void sendCode(String phone) {
        //校验手机号码格式是否正确
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }

        //生成随机验证码
        String code = RandomStringUtils.randomNumeric(6);

        //保存到redis缓存中,有效时间为5分钟
        String key = KEY_PREFIX + phone;
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

        //利用ampq给RabbitMQ发送消息,进行短信发送
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用户注册
     *
     * @param user 表单提交数据
     * @param code 验证码
     */
    @Transactional
    @Override
    public void register(User user, String code) {
        if (null == user || StringUtils.isBlank(code)) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        // 验证短信验证码
        String key = KEY_PREFIX + user.getPhone();
        String verifyCode = redisTemplate.opsForValue().get(key);
        if (!StringUtils.equals(verifyCode, code)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        // 校验用户数据

        // 对密码加密,并替换原来的密码
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);

        // 写入数据库
        int count = userMapper.insertSelective(user);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 根据参数中的用户名和密码查询指定用户并且返回用户
     *
     * @param username 用户名
     * @param password 密码
     * @return 用户的json格式
     */
    @Override
    public String queryUserByUsernameAndPassword(String username, String password) {
        /*
        因为username建立了索引,password没有建立索引,
        直接根据username查询,
        再把查出来的user的password和传过来的password进行比较
        */
        //1.校验username
        if (StringUtils.isBlank(username)) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //2.根据用户名username查询用户user
        User user = new User();
        user.setUsername(username);
        User selectedUser = userMapper.selectOne(user);
        if (null == selectedUser) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //3.将用户user的密码password和参数password进行比较(注意:参数password未加密)
        if (!passwordEncoder.matches(password, selectedUser.getPassword())) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //4.用户user转换成userDTO,再转换成json,并返回
        String user_json = JsonUtils.toString(BeanHelper.copyProperties(selectedUser, UserDTO.class));
        return user_json;
    }
}
